using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Caece.Libreria.FrontEnd;
using Caece.Libreria.DNS;
using System.Threading;
using Caece.Libreria.Protocolo;
using System.Diagnostics; 


namespace Caece.Libreria.Manager      
{   
    public partial class Main : Form
    {
		int _dnsPort;
		string _dnsIP;
		clsDNS _dns;
		int _dnsTimeOut;
		int _frontEndTimeOut;
		static int _initialPort;
		
		ClientInfo[] _clientesInfo;
		FrontEndInfo[] _frontEndsInfo;
		Process[] _frontEndProcess;
        Process[] _clientesProcess;


		public Main()
		{
			_initialPort = 9000;
			_dnsPort = Util.GetConfig<int>("DNS_Port");
			_dnsIP = Util.GetConfig<string>("DNS_IP");
			_dnsTimeOut = Util.GetConfig<int>("DNS_TimeOut");

			_frontEndTimeOut = Util.GetConfig<int>("FrontEnd_TimeOut");

			InitializeComponent();
			this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
		}

		void Form1_FormClosing(object sender, FormClosingEventArgs e)
		{
			// Clientes
			if (_clientesInfo != null)
			{
				foreach (ClientInfo info in _clientesInfo)
				{
					if (info != null && info.Thread != null)
						info.Thread.Abort();
				}
			}

			// FrontEnd
			if (_frontEndsInfo != null)
			{
				foreach (FrontEndInfo info in _frontEndsInfo)
				{
					if (info.FrontEnd != null)
						info.FrontEnd.Stop();

					if (info != null && info.Thread != null)
						info.Thread.Abort();
				}
			}
		}

		public void IniciarNodoFrontEnd(BerkeleyNode server)
		{
			server.Start();
		}

		private void button7_Click(object sender, EventArgs e)
		{
			/*
			_dns = new clsDNS(_dnsPort, _dnsTimeOut);
			_dns.Start();*/

			//Start DNS
			Process DNS = new Process();
			DNS.StartInfo.FileName = Util.GetConfig<string>("DNS_AppPath");
			DNS.StartInfo.Arguments = "";
			DNS.Start();
		}

		private void button10_Click(object sender, EventArgs e)
		{
			int cantidad = Convert.ToInt32(numFrontEnds.Value);
			
			_frontEndProcess = new Process[cantidad];
			for (int i = 0; i < cantidad; i++)
			{
				/*
				FrontEndInfo info = new FrontEndInfo();
				_frontEndsInfo[i] = info;
				info.FrontEnd = new BerkeleyNode(_frontEndTimeOut, port, _dnsIP, _dnsPort, new TimeSpan());
				info.Port = port;
				info.Thread = new Thread(TestThread2);
				info.Thread.Start(info);
				*/
				_initialPort++;
				_frontEndProcess[i] = new Process();
				_frontEndProcess[i].StartInfo.FileName = Util.GetConfig<string>("FrontEnd_AppPath");
				_frontEndProcess[i].StartInfo.Arguments = _initialPort.ToString();
				_frontEndProcess[i].Start();
			}		
		}

		private void TestThread2(object info)
		{
			FrontEndInfo i = (FrontEndInfo)info;
			i.FrontEnd = new BerkeleyNode(_frontEndTimeOut, i.Port, _dnsIP, _dnsPort, new TimeSpan());
			i.FrontEnd.Start();
		}

		private void button8_Click_1(object sender, EventArgs e)
		{
			if (_dns != null)
				_dns.Stop();
		}

		private void button1_Click(object sender, EventArgs e)
		{
			if (_dns != null)
			{
				StringBuilder sb = new StringBuilder();

				List<clsInfo> nodos = _dns.ObtenerLista();
				foreach (clsInfo nodo in nodos)
					sb.AppendLine(String.Format("Id:{0} {1}:{2}", nodo.ProcesoId, nodo.Ip, nodo.Puerto));

				MessageBox.Show(sb.ToString());
			}
		}

		private void button3_Click(object sender, EventArgs e)
		{
			/*
			Execution1[] operaciones = null;
            
			/*int cantidad = Convert.ToInt32(numClientes.Value);
			_clientesInfo = new ClientInfo[cantidad];
			for (int i = 0; i < cantidad; i++)
			{
				ClientInfo info = new ClientInfo();
				_clientesInfo[i] = info;
				info.Cliente = new Cliente1(_dnsIP, _dnsPort);
				info.Thread = new Thread(info.Cliente.Automatic);
				//info.Thread = new Thread(info.Cliente.);
				info.Thread.Start();
			}*/
            
            
		

            int cantidad = Convert.ToInt32(numClientes.Value);
            _clientesProcess = new Process[cantidad];
            for (int i = 0; i < cantidad; i++)
            {
                _clientesProcess[i] = new Process();
				_clientesProcess[i].StartInfo.FileName = Util.GetConfig<string>("Client_AppPath");
                _clientesProcess[i].Start();
				Thread.Sleep(200);

            }

		}

		private void button4_Click(object sender, EventArgs e)
		{
			ClientInfo info = new ClientInfo();
			info.Cliente = new Cliente1(_dnsIP, _dnsPort);
			MessageBox.Show(info.Cliente.ComprarItem(Convert.ToInt32(txtArgumentoClient.Text)));
		}

		private void button6_Click(object sender, EventArgs e)
		{
			Thread t = new Thread(TestThread);
			t.Start();
		}

		private void button12_Click(object sender, EventArgs e)
		{
			ClientInfo info = new ClientInfo();
			info.Cliente = new Cliente1(_dnsIP, _dnsPort);
			MessageBox.Show(info.Cliente.ConsultarPorTema(txtArgumentoClient.Text));
		}

		private void TestThread()
		{
			ClientInfo info = new ClientInfo();
			info.Cliente = new Cliente1(_dnsIP, _dnsPort);
			MessageBox.Show(info.Cliente.ConsultarPorItem(Convert.ToInt32(txtArgumentoClient.Text)));
		}

		private void panel1_Paint(object sender, PaintEventArgs e)
		{

		}

		private void button1_Click_1(object sender, EventArgs e)
		{
			for (int i = 0; i < _clientesProcess.Length; i++)
			{
				try
				{
					_clientesProcess[i].CloseMainWindow();
				}
				catch
				{ 
				}
			}

			for (int i = 0; i < _frontEndProcess.Length; i++)
			{
				try
				{
					_frontEndProcess[i].CloseMainWindow();
				}
				catch
				{ 
				}
			}
		}

		private void button2_Click(object sender, EventArgs e)
		{
			DateTime[] horas = new DateTime[2];
			long promedio = 0;

			// Pregunto la hora a todos los nodos
			horas[0] = new DateTime(2008, 11, 26, 9, 0, 10, DateTimeKind.Local);
			horas[1] = new DateTime(2008, 11, 26, 9, 0, 20, DateTimeKind.Local);

			for (int i = 0; i < horas.Length; i++)
			{
				promedio += (horas[i].Ticks / 10000);
			}

			// Calculo la hora oficial
			DateTime horaOficial = new DateTime((promedio / horas.Length) * 10000);

			// Informo a todos los nodos el delta a ajustar
			for (int i = 0; i < horas.Length; i++)
			{
				TimeSpan deltaTime = (horaOficial - horas[i]);
				string delta = deltaTime.ToString();
			}
		}

		private void button6_Click_1(object sender, EventArgs e)
		{
			ClientInfo info = new ClientInfo();
			info.Cliente = new Cliente1(_dnsIP, _dnsPort);
			MessageBox.Show(info.Cliente.ConsultarPorItem(Convert.ToInt32(txtArgumentoClient.Text)));
		}

		private void button4_Click_1(object sender, EventArgs e)
		{
			ClientInfo info = new ClientInfo();
			info.Cliente = new Cliente1(_dnsIP, _dnsPort);
			MessageBox.Show(info.Cliente.ComprarItem(Convert.ToInt32(txtArgumentoClient.Text)));
		
		}

		private void button12_Click_1(object sender, EventArgs e)
		{
			ClientInfo info = new ClientInfo();
			info.Cliente = new Cliente1(_dnsIP, _dnsPort);
			MessageBox.Show(info.Cliente.ConsultarPorTema(txtArgumentoClient.Text));
		}
						
    }
}